package easydevelop.popup.actions;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import easydevelop.EasydevelopPlugin;

public class ExploreAction implements IObjectActionDelegate {

	private Object currentResource = null;

	private String EXPLORE_ACTION_ID = null;

	private String EXPLORE_CMD = null;

	private String DEBUG_FLAG = null;

	/**
	 * Constructor for Action1.
	 */
	public ExploreAction() {
		super();
		EXPLORE_ACTION_ID =
			EasydevelopPlugin.getResourceString("explore.action.id");
		EXPLORE_CMD = EasydevelopPlugin.getResourceString("explore.cmd");
		DEBUG_FLAG = EasydevelopPlugin.getResourceString("debug.flag");
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		try {
			if (!EXPLORE_ACTION_ID.equals(action.getId())) {
				return;
			}

			String path = null;
			String param = "/n,";

			if (currentResource instanceof IFile) {
				IFile tmpFile = (IFile) currentResource;
				path = tmpFile.getLocation().toString().replace('/', '\\');
				param = param + "/select," + path;
			} else if (currentResource instanceof IFolder) {
				IFolder tmpFolder = (IFolder) currentResource;
				path = tmpFolder.getLocation().toFile().getPath();
				param = param + path;
			} else if (currentResource instanceof IProject) {
				IProject tmpProject = (IProject) currentResource;
				path = tmpProject.getLocation().toFile().getPath();
				param = param + path;
			}

			if ("on".equals(DEBUG_FLAG)) {
				Shell shell = new Shell();
				MessageDialog.openInformation(
					shell,
					"easydevelop Plug-in",
					EXPLORE_CMD + " " + path);
			}
			Runtime run = Runtime.getRuntime();
			run.exec(new String[] { EXPLORE_CMD, param });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		if (EXPLORE_ACTION_ID.equals(action.getId())) {
			if (selection instanceof StructuredSelection) {
				StructuredSelection ss = (StructuredSelection) selection;
				this.currentResource = ss.getFirstElement();
			}
		}
	}

}
